import React from 'react'
import PropTypes from 'prop-types'
import initGeetest from '@/utils/gt'
import { Spin, Icon } from 'antd'
import styles from './index.less'

class Geetest extends React.Component {

  shouldComponentUpdate(nextProps) {
    const { success } = this.props
    if (nextProps.success === success) {
      return false
    }
    return true
  }

  componentDidUpdate() {
    this.init()
  }

  init = () => {
    // eslint-disable-next-line
    const { gt, challenge, success, new_captcha, verify_code, handlerGeetest } = this.props

    initGeetest({
      // 以下 4 个配置参数为必须，不能缺少
      gt,
      challenge,
      offline: !success, // 表示用户后台检测极验服务器是否宕机
      new_captcha, // 用于宕机时表示是新验证码的宕机

      product: 'float', // 产品形式，包括：float，popup
      width: '312px'
      // 更多配置参数说明请参见：http://docs.geetest.com/install/client/web-front/
    }, (captchaObj) => {
      this.captchaNode.innerHTML = ''
      captchaObj.appendTo(this.captchaNode)
      handlerGeetest(captchaObj)
    })
  }

  render() {
    return (
      <section className={styles.captcha} ref={captchaNode => {this.captchaNode = captchaNode}}>
        <Spin tip={<a href='/'>点我刷新</a>} indicator={<Icon type='loading' style={{ fontSize: 24 }} spin />} />
      </section>
    )
  }
}

Geetest.propTypes = {
  gt: PropTypes.string,
  challenge: PropTypes.string,
  success: PropTypes.number,
  new_captcha: PropTypes.bool,
  verify_code: PropTypes.string,
  handlerGeetest: PropTypes.func
}

Geetest.defaultProps = {
  gt: '',
  challenge: '',
  success: 0,
  new_captcha: false,
  verify_code: '',
  handlerGeetest: () => {}
}

export default Geetest